﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using MiragePWF.Common.Container;
using Wolfut.MirageEE.Domain.Common;
using Wolfut.MirageEE.Domain.CommonUtilities;
using Wolfut.MirageEE.Server.Server.Common;
using Wolfut.MirageEE.Interface.Common;
using Wolfut.MirageEE.UI.UICommonUtilities;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;

namespace Wolfut.MirageEE.UI.UIBaseComponents
{
    /// <summary>
    /// todo 1:UI change workflow 2:data rowindex 3:enity validation 4:exception hanlder 5:form closing
    /// </summary>
    public partial class UserBillCodeRuleControl : MirageEEUserControlBase
    {
        #region Private Var
        private Constant.FormState formState = Constant.FormState.FORMADD;
        ICodeRulesService service;
        IList<CodeRule> listCodeRule = null;
        #endregion

        #region Property
        private String _codeFlag = Constant.CodeRuleConst.COLLECTING_BILLS;
        public String CodeFlag
        {
            get
            {
                return _codeFlag;
            }
            set
            {
                _codeFlag = value;
            }
        }
        public GridView GridCodeRule
        {
            get
            {
                return this.gridViewCodeRules;
            }
        }        
        #endregion

        #region Init
        public UserBillCodeRuleControl()
        {
            InitializeComponent();
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            ddlNumberWidth.Properties.MinValue = 1;
            ddlNumberWidth.Properties.MaxValue = 9;
            ddlStartNo.Properties.MinValue = 1;
            ddlStartNo.Properties.MaxValue = int.MaxValue;
            rgCodeMethod.SelectedIndex = 0;
            rgYearWidth.SelectedIndex = 0;
            rgYearWidth.Enabled = false;
            
            SimpleButtonSave.Click += new System.EventHandler(this.SimpleButtonSave_Click);            
            gridViewCodeRules.DoubleClick += new EventHandler(this.gridViewCodeRules_DoubleClick);
            SimpleButtonClear.Click += new EventHandler(SimpleButtonClear_Click);
            txtCodePre.LostFocus += new EventHandler(this.OnSample);
            ddlNumberWidth.LostFocus += new EventHandler(this.OnSample);
            ddlStartNo.LostFocus += new EventHandler(this.OnSample);
            rgCodeMethod.SelectedIndexChanged += new EventHandler(this.rgCodeMethod_SelectedIndexChanged);
            rgYearWidth.SelectedIndexChanged += new EventHandler(this.rgYearWidth_SelcetedIndexChanged);
            gridViewCodeRules.CustomUnboundColumnData += new CustomColumnDataEventHandler(this.gridViewCodeRules_CustomUnboundColumnData);                   
        }
        #endregion

        #region 绑定数据
        private void gridViewCodeRules_CustomUnboundColumnData(object sender, CustomColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "IsDefault")
            {
                //get this row
                CodeRule cc = this.gridViewCodeRules.GetRow(e.RowHandle) as CodeRule;
                //to do Bruce.huang 是否默认
                e.Value = cc.IsDefault ? Constant.SysTrueCode : Constant.SysFalseCode;
            }
        }
        protected override void BindGrid(bool IsDBLoading)
        {
            if (IsDBLoading)
            {
                if (service == null)
                {
                    service = IOC.Resolve<ICodeRulesService>();
                }
                listCodeRule = service.ListCodeRulesByCodeFlag(this.CodeFlag, false);
            }
            gridControlCodeRules.DataSource = listCodeRule;
            this.SetFormInformation();
            RefreshGridViewEx();
        }
        #endregion

        #region 保存
        protected override bool isValid()
        {
            //check form controls' validation
            if (String.IsNullOrEmpty(txtRuleName.Text.Trim()))
            {
                CustomerShowMessage.ShowMessage("E00001", "规则名称");
                txtRuleName.Focus();
                return false;
            }
            if (String.IsNullOrEmpty(txtCodePre.Text.Trim()))
            {
                CustomerShowMessage.ShowMessage("E00001", "编码前缀");
                txtCodePre.Focus();
                return false;
            }

            return true;
        }
        private void SimpleButtonSave_Click(object sender, EventArgs e)
        {
            if (!this.isValid())
            {
                return;
            }
            try
            {
                Cursor = Cursors.WaitCursor;
                if ((this.formState == Constant.FormState.FORMADD)
                    || (this.formState == Constant.FormState.FORMITEMCOPY))
                {                    
                    CodeRule codeRuleItem = new CodeRule();
                    codeRuleItem.CodeFlag = this.CodeFlag;
                    codeRuleItem.CodePre = txtCodePre.Text;
                    codeRuleItem.RuleName = txtRuleName.Text;
                    codeRuleItem.RuleWidth = (int)ddlNumberWidth.Value;
                    codeRuleItem.StartNo = (int)ddlStartNo.Value;
                    if (rgIsDefault.SelectedIndex == 0)
                    {
                        codeRuleItem.IsDefault = true;
                    }
                    else
                    {
                        codeRuleItem.IsDefault = false;
                    }
                    codeRuleItem.CodeManner = (CodeManner)Enum.Parse(typeof(CodeManner), rgCodeMethod.SelectedIndex.ToString());
                    if(codeRuleItem.CodeManner!=CodeManner.No)
                    {
                        if (rgYearWidth.SelectedIndex == 0)
                        {
                            codeRuleItem.YearWidth = 4;
                        }
                        else
                        {
                            codeRuleItem.YearWidth = 2;
                        }
                        
                    }
                    listCodeRule.Add(codeRuleItem);
                    this.CurrentRow = codeRuleItem;
                }
                if (this.formState == Constant.FormState.FORMUPDATED)
                {
                    CodeRule codeRuleItem = CurrentRow as CodeRule;
                    codeRuleItem.CodeFlag = this.CodeFlag;
                    codeRuleItem.CodePre = txtCodePre.Text;
                    codeRuleItem.RuleName = txtRuleName.Text;
                    codeRuleItem.RuleWidth = (int)ddlNumberWidth.Value;
                    codeRuleItem.StartNo = (int)ddlStartNo.Value;
                    if (rgIsDefault.SelectedIndex == 0)
                    {
                        codeRuleItem.IsDefault = true;
                    }
                    else
                    {
                        codeRuleItem.IsDefault = false;
                    }
                    this.CurrentRow = codeRuleItem;
                }
                service.AddOrUpdateCodeRule(this.CurrentRow as CodeRule);
                CustomerShowMessage.ShowMessage("I20007");
                this.BindGrid(false);
                this.Owner.Dirty = false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        public void RefreshGridViewEx()
        {
            if (gridViewCodeRules.RowCount > 0)
            {

                if (this.formState == Constant.FormState.FORMADD)
                {
                    gridViewCodeRules.MoveLast();
                }

            }
            GridOperations.RefreshGridView(gridViewCodeRules);
        }
        #endregion

        #region 重置
        private void SimpleButtonClear_Click(object sender, EventArgs e)
        {
            this.formState = Constant.FormState.FORMADD;
            this.SetFormInformation();
            this.Owner.Dirty = false;
        }
        #endregion

        #region Sample
        protected virtual void OnSample(object sender, EventArgs e)
        {
            this.txtSample.Text = this.GenerateSample();
        }
        private String GenerateSample()
        {
            #region Generated CodeRule Sample
            StringBuilder strSample = new StringBuilder();
            if (!String.IsNullOrEmpty(txtCodePre.Text.Trim()))
            {
                strSample.Append(txtCodePre.Text.Trim());
            }
            if (rgCodeMethod.SelectedIndex != 0)
            {
                if (rgYearWidth.SelectedIndex == 0)
                {
                    strSample.Append("YYYY");
                }
                else
                {
                    strSample.Append("YY");
                }
                if (rgCodeMethod.SelectedIndex == 2)
                {
                    strSample.Append("MM");
                }
                if (rgCodeMethod.SelectedIndex == 3)
                {
                    strSample.Append("MMDD");
                }
            }
            for (int ii = 0; ii < ddlNumberWidth.Value - ddlStartNo.Value.ToString().Length; ii++)
            {
                strSample.Append("0");
            }
            strSample.Append(ddlStartNo.Value.ToString());
            #endregion
            return strSample.ToString();
        }
        private void rgCodeMethod_SelectedIndexChanged(object sender, EventArgs e)
        {
            rgYearWidth.SelectedIndex = 0;
            if (rgCodeMethod.SelectedIndex == 0)
            {
                rgYearWidth.Enabled = false;
            }
            else
            {
                rgYearWidth.Enabled = true;
            }
            this.txtSample.Text = this.GenerateSample();
        }
        private void rgYearWidth_SelcetedIndexChanged(object sender, EventArgs e)
        {
            this.txtSample.Text = this.GenerateSample();
        }
        #endregion       

        #region 删除/导出
        private void gridViewCodeRules_DoubleClick(object sender, EventArgs e)
        {
            this.formState = Constant.FormState.FORMUPDATED;
            this.RowIndex = gridViewCodeRules.FocusedRowHandle;
            this.CurrentRow = this.gridViewCodeRules.GetRow(this.RowIndex) as CodeRule;
            SetFormInformation();
            ////data is not changed
            this.Owner.Dirty = false;
            
        }
        private void SetFormInformation()
        {
            //复制、修改
            if ((this.formState == Constant.FormState.FORMUPDATED)
               || (this.formState == Constant.FormState.FORMUPDATED))
            {
                if (this.CurrentRow == null)
                {
                    return;
                }
                CodeRule item = (CodeRule)this.CurrentRow;
                this.txtRuleName.Text = item.RuleName;
                this.txtCodePre.Text = item.CodePre;
                if (item.IsDefault)
                {
                    this.rgIsDefault.SelectedIndex = 0;
                }
                else
                {
                    this.rgIsDefault.SelectedIndex = 1;
                }
                this.ddlNumberWidth.Text = item.RuleWidth.ToString();
                this.ddlStartNo.Text = item.StartNo.ToString();
            }
            if (this.formState == Constant.FormState.FORMADD)
            {
                txtCodePre.EditValue = String.Empty;
                txtRuleName.EditValue = String.Empty;
                txtSample.EditValue = String.Empty;
                rgIsDefault.SelectedIndex = 0;
                ddlStartNo.EditValue = 1;
                ddlNumberWidth.EditValue = 1;
                this.groupControlDetail.Text = String.Format(Constant.FormAddText, Constant.ModuleName.CodeRuleText);
            }
            if (this.formState == Constant.FormState.FORMUPDATED)
            {
                this.groupControlDetail.Text = String.Format(Constant.FormModifyText, Constant.ModuleName.CodeRuleText);
            }
            if (this.formState == Constant.FormState.FORMITEMCOPY)
            {
                this.groupControlDetail.Text = String.Format(Constant.FormAddText, Constant.ModuleName.CodeRuleText);
            }
        }        
        public virtual void OnAllDeleted(EventArgs e)
        {
            int[] selectedRow = GridOperations.CheckGridViewSelectedCount(gridViewCodeRules, true);
            if (selectedRow == null) return;
            //确认是否删除
            if (!CustomerShowMessage.ConfirmProceed(String.Empty))
            {
                return;
            }
            foreach (int ii in selectedRow)
            {
                CodeRule item = (CodeRule)gridViewCodeRules.GetRow(ii);
                item.IsDeleted = true;
                service.AddOrUpdateCodeRule(item);
            }
            this.BindGrid(true);
            this.Owner.Dirty = false;
        }
        #endregion       
    }
}
